# -*- coding:utf-8 -*-
import requests
import re
import json
from bs4 import BeautifulSoup
#添加请求头
HEADERS = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
}
def getYoudaoWebByWord(word):
    resp = requests.get('https://dict.youdao.com/result?word=%s&lang=en' % word,headers = HEADERS)
    return resp.text
def getPattern(exp):
    return re.compile(exp)
def getTargetList(exp,content):
    p = re.compile(exp)
    return p.findall(content)

#-------- 使用有道词典json格式api获取翻译信息 begin --------#
HEADERS_FOR_YOUDAO_JSON = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
URL_YOUDAO_JSON = 'https://dict.youdao.com/jsonapi?q='
#一次请求获取全部需要的单词属性数据
def getYoudaoJsonAllByWord(word):
    url = URL_YOUDAO_JSON + f'{word}'
    global phonetics_and_prototype
    global word_means_str_for_markdown
    try:
        response = requests.get(url, headers=HEADERS_FOR_YOUDAO_JSON)
        response.raise_for_status()
        data = response.json()
        # 提取音标
        if 'simple' in data:
            simple_data = data['simple']
            if 'word' in simple_data and len(simple_data['word']) > 0:
                word_data = simple_data['word'][0]
                if 'ukphone' in word_data and 'usphone' in word_data:
                    uk_phonetic = word_data['ukphone']
                    us_phonetic = word_data['usphone']
                    phonetics = f"uk: /{uk_phonetic}/<br>us: /{us_phonetic}/"
        # 提取音标和释义 赋值给全局变量 phonetics_and_prototype = {}和 word_means_str_for_markdown = ''
        if 'ec' in data:
            traverse_json_for_word(data['ec'])
            traverse_json_for_word_trs_means(word_means_list)
            pap = phonetics_and_prototype
            wmm = word_means_str_for_markdown
        phonetics_and_prototype = {}
        word_means_str_for_markdown = ''
        return pap,wmm
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except (KeyError, IndexError, json.JSONDecodeError):
        print(f'查询{word}解析数据时出错，可能是接口返回格式有变化。')
    phonetics_and_prototype = {}
    word_means_str_for_markdown = ''
    return f'未找到单词{word}的数据。'

#单词词义
def getYoudaoJsonMeanByWord(word):
    url = URL_YOUDAO_JSON + f'{word}'
    global word_means_str_for_markdown
    try:
        response = requests.get(url, headers=HEADERS_FOR_YOUDAO_JSON)
        response.raise_for_status()
        data = response.json()
        if data != None or data != {}:
            trs = data['ec']['word']
            #print(trs)
            traverse_json_for_word_trs_means(trs)
            word_mean_market = word_means_str_for_markdown
            word_means_str_for_markdown = ''
            return word_mean_market[4:] # 去掉开头的<br>标签
        else:
            url = URL_YOUDAO_JSON + f'{word.lower()}'
        response = requests.get(url, headers=HEADERS_FOR_YOUDAO_JSON)
        response.raise_for_status()
        data = response.json()
        if data != None or data != {}:
            trs = data['ec']['word']
            #print(trs)
            traverse_json_for_word_trs_means(trs)
            word_mean_market = word_means_str_for_markdown
            word_means_str_for_markdown = ''
            return word_mean_market[4:] # 去掉开头的<br>标签
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except (KeyError, IndexError, json.JSONDecodeError):
        print(f'查询{word}解析数据时出错，可能是接口返回格式有变化。')
    return f'未找到单词{word}的词义数据。'

#单词音标
def getYoudaoJsonPhoneticByWord(word):
    url = URL_YOUDAO_JSON + f'{word}'
    try:
        response = requests.get(url, headers=HEADERS_FOR_YOUDAO_JSON)
        response.raise_for_status()
        data = response.json()
        # 提取音标信息
        if 'simple' in data:
            simple_data = data['simple']
            if 'word' in simple_data and len(simple_data['word']) > 0:
                uk_phonetic = us_phonetic = None
                word_data = simple_data['word'][0]
                if 'ukphone' in word_data:
                    uk_phonetic = word_data['ukphone']
                if 'usphone' in word_data:
                    us_phonetic = word_data['usphone']
                if uk_phonetic and us_phonetic:
                    return f"uk: /{uk_phonetic}/<br>us: /{us_phonetic}/"
                elif us_phonetic:
                    return f"us: /{us_phonetic}/"
                elif uk_phonetic:
                    return f"uk: /{uk_phonetic}/"
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except (KeyError, IndexError, json.JSONDecodeError):
        print(f'查询{word}解析数据时出错，可能是接口返回格式有变化。')
    return ''

# 测试示例
#word = "wonder"
#phonetic_info = getYoudaoJsonPhoneticByWord(word)
#print(f"{word}: {phonetic_info}")

#句子中文翻译
def getYoudaoJsonBySentence(sentence):
    url = URL_YOUDAO_JSON + f'{sentence}'
    try:
        response = requests.get(url, headers=HEADERS_FOR_YOUDAO_JSON)
        response.raise_for_status()
        data = response.json()
        # 提取翻译信息
        if 'fanyi' in data:
            fanyi_data = data['fanyi']
            if 'tran' in fanyi_data and len(fanyi_data['tran']) > 0:
                tran_data = fanyi_data['tran']
                return tran_data
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except (KeyError, IndexError, json.JSONDecodeError):
        print("解析数据出错，可能是接口返回格式有变化。")
    return "未找到句子的翻译信息。"
#-------- 使用有道词典json格式api获取翻译信息 end --------#

def getWordMean(word):
    html = getYoudaoWebByWord(word).replace('\n','').replace('\t','').replace('\r','')
    #--------bs4 process begin--------#
    #with open('C:/E/temp/pic/neglect.html','r',encoding='utf-8') as htmlfile:
    #    html = htmlfile.read()
    bsp = BeautifulSoup(html,'html.parser')
    phonetic_list = bsp.select('.phonetic')
    word_dict_list = bsp.select('ul.basic')
    word_dict_list = str(word_dict_list).replace('<p','<span').replace('</p>','</span>')
    web_phrase_list = bsp.select('div.webPhrase > ul > li.mcols-layout')
    web_phrase_list = str(web_phrase_list).replace('<p','<span').replace('</p>','</span>').replace(',','')
    phrs_list = bsp.select('div.phrs.dict-module > ul.trans-container > li')
    phrs_list = str(phrs_list).replace(',','')
    #--------bs4 process end----------#
    text = '%s\n%s\n%s\n%s\n' % (phonetic_list,word_dict_list,web_phrase_list,phrs_list)
    return text

def getYoudaoWebBySentenceMean(sentence):
    '''https://dict.youdao.com/result?word=%s&lang=en'''
    resp = requests.get('https://dict.youdao.com/result?word=%s&lang=en' % sentence,headers = HEADERS)
    return resp.text

def getSentenceMean(sentence):
    html = getYoudaoWebBySentenceMean(sentence).replace('\n','').replace('\t','').replace('\r','')
    #with open('C:/E/temp/pic/sentence.html','r',encoding='utf-8') as sentencefile:
    #    html = sentencefile.read()
    bsp = BeautifulSoup(html,'html.parser')
    texts = bsp.select('.trans-content')
    sentence = ''
    for _t in texts:
        sentence = sentence + _t.get_text()
    return sentence

current_tag = ''
phonetics_and_prototype = {}
word_means_list = []
word_means_str_for_markdown = ''

def traverse_json_for_word(data):
    if isinstance(data, dict):
        for key, value in data.items():
            if key in ['ukphone','usphone','prototype']:
                phonetics_and_prototype[key] = value
            global current_tag 
            current_tag = key
            traverse_json_for_word(value)
    elif isinstance(data, list):
        if current_tag == 'trs':
            global word_means_list
            word_means_list = data
        for item in data:
            traverse_json_for_word(item)

def traverse_json_for_word_trs_means(data):
    if isinstance(data, dict):
        for key, value in data.items():
            traverse_json_for_word_trs_means(value)
    elif isinstance(data, list):
        for item in data:
            if not isinstance(item, list) and not isinstance(item, dict):
                global word_means_str_for_markdown
                word_means_str_for_markdown += f'<br>{item}'
            traverse_json_for_word_trs_means(item)

if __name__ == '__main__':
    try:
        #print(getSentenceMean('the Chinese nation will never succumb to blackmail or sheer pressure.'))
        #print(getYoudaoJsonBySentence('At this point you’re probably after an explanation.'))
        #print(getYoudaoJsonPhoneticByWord('wonder'))
        print(getYoudaoJsonMeanByWord('wonder'))
    except Exception as ex:
        print('__main__::: ' + str(ex))
    finally:
        pass